/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-26，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.ui.activity;

import java.util.Map;
import com.chinamobile.ln.ictenterprises.R;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.Constants;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;
import com.chinamobile.ln.ictenterprises.http.HttpSend;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.model.request.Login;
import com.chinamobile.ln.ictenterprises.model.response.ResponseLogin;
import com.chinamobile.ln.ictenterprises.utils.JsonUtil;
import com.chinamobile.ln.ictenterprises.utils.ValidateUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class LoginActivity extends ParentActivity implements OnClickListener,
    OnCheckedChangeListener
{
    private EditText et_id, et_name, et_password;
    private RelativeLayout login_btn;
    private String ictid, username, password, alias, smsSign;
    private CheckBox rmb_pwd, auto_login;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.user_login_layout);
    }

    @Override
    protected void setupView()
    {
        et_id = (EditText) findViewById(R.id.ict_id);
        et_name = (EditText) findViewById(R.id.user_name);
        et_password = (EditText) findViewById(R.id.pass_word);
        login_btn = (RelativeLayout) findViewById(R.id.login_btn);
        rmb_pwd = (CheckBox) findViewById(R.id.rmb_password_check);
        rmb_pwd.setOnCheckedChangeListener(this);
        auto_login = (CheckBox) findViewById(R.id.auto_login_check);
        auto_login.setOnCheckedChangeListener(this);
        login_btn.setOnClickListener(this);
    }

    @Override
    protected void setupData()
    {
        initConfig();
    }

    /** 初始化配置 **/
    private void initConfig()
    {
        et_id.setText(sharedPref.getString(Constants.LOGIN_ICTID, null));
        et_name.setText(sharedPref.getString(Constants.LOGIN_USERNAME, null));
        et_password.setText(sharedPref
            .getString(Constants.LOGIN_PASSWORD, null));
        rmb_pwd.setChecked(sharedPref.getBoolean(Constants.LOGIN_REMEMBERPSW,
            false));
        auto_login.setChecked(sharedPref.getBoolean(Constants.LOGIN_AUTOLOGIN,
            false));
        if (sharedPref.getBoolean(Constants.LOGIN_AUTOLOGIN, false))
        {
            login();
        }
    }

    /**
     * 登录
     */
    private void login()
    {
        ictid = et_id.getText().toString();
        username = et_name.getText().toString();
        password = et_password.getText().toString();
        if (ValidateUtil.isEmpty(ictid))
        {
            showTip(R.string.input_id_hint);
            et_id.requestFocus();
            return;
        }
        if (ValidateUtil.isEmpty(username))
        {
            showTip(R.string.input_name_hint);
            et_name.requestFocus();
            return;
        }
        if (ValidateUtil.isEmpty(password))
        {
            showTip(R.string.input_password_hint);
            et_password.requestFocus();
            return;
        }
        if (!checkNet(context))
        {
            showTip(R.string.network_fail);
            return;
        }
        Login login = new Login(GlobalSetting.LOGIN, ictid, username, password);
        String params = JsonUtil.objectToJson(login);
        showProgressDialog("正在登录,请稍等...");
        login_btn.setClickable(false);
        Step step = new Step();
        step.setUrl(Config.USER_LOGIN);
        step.setStreamString(params);
        step.setEncoding("UTF-8");
        step.setRequestType(HttpSend.JSON_REQUEST);
        HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
            HttpAsyncTask.CACHE_TYPE_ACTION, "", GlobalSetting.USER_LOGIN);
        httpAsyncTask.setUIHandler(loginHandler);
        mHttpManager.execute(httpAsyncTask);
    }

    private Handler loginHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            if (msg.obj != null)
            {
                @SuppressWarnings("unchecked")
                Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                int reultCode = (Integer) httpMap
                    .get(GlobalSetting.STUATUS_CODE);
                if (reultCode == GlobalSetting.STUATUS_CODE_SUCCESS)
                {
                    ResponseLogin responseLogin = (ResponseLogin) httpMap
                        .get(GlobalSetting.JSON_USER_LOGIN);
                    if (responseLogin != null)
                    {
                        if (responseLogin.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_SUC))
                        {
                            alias = responseLogin.results.alias;
                            smsSign = responseLogin.results.smsSign;
                            sharedPref
                                .edit()
                                .putString(
                                    Constants.COOKIES,
                                    (String) httpMap
                                        .get(GlobalSetting.TMP_COOKIES))
                                .commit();
                            updateSharedPref();
                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this,
                                MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                        else if (responseLogin.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_FAIL))
                        {
                            sharedPref.edit()
                                .putString(Constants.LOGIN_PASSWORD, "")
                                .commit();
                            sharedPref.edit().putString(Constants.ALIAS, "")
                                .commit();
                            sharedPref.edit().putString(Constants.SMS_SIGN, "")
                                .commit();
                            Toast.makeText(context,
                                responseLogin.results.errorMsg,
                                Toast.LENGTH_SHORT).show();
                        }
                    }
                    else
                    {
                        Toast.makeText(context, R.string.login_fail2,
                            Toast.LENGTH_SHORT).show();
                    }
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_TIMEROUT)
                {
                    Toast.makeText(context, R.string.login_fail3,
                        Toast.LENGTH_SHORT).show();
                }
            }
            dismissProgressDialog();
            login_btn.setClickable(true);
        };
    };

    /**
     * 记住密码和自动登录
     */
    private void updateSharedPref()
    {
        sharedPref.edit().putString(Constants.ALIAS, alias).commit();
        sharedPref.edit().putString(Constants.SMS_SIGN, smsSign).commit();
        if (auto_login.isChecked())
        {
            sharedPref.edit().putString(Constants.LOGIN_USERNAME, username)
                .commit();
            sharedPref.edit().putString(Constants.LOGIN_PASSWORD, password)
                .commit();
            sharedPref.edit().putBoolean(Constants.LOGIN_REMEMBERPSW, true)
                .commit();
            sharedPref.edit().putBoolean(Constants.LOGIN_AUTOLOGIN, true)
                .commit();
        }
        if (rmb_pwd.isChecked())
        {
            sharedPref.edit().putString(Constants.LOGIN_ICTID, ictid).commit();
            sharedPref.edit().putString(Constants.LOGIN_USERNAME, username)
                .commit();
            sharedPref.edit().putString(Constants.LOGIN_PASSWORD, password)
                .commit();
        }
        else
        {
            sharedPref.edit().putString(Constants.LOGIN_PASSWORD, "").commit();
        }
        sharedPref.edit()
            .putBoolean(Constants.LOGIN_REMEMBERPSW, rmb_pwd.isChecked())
            .commit();
    }

    @Override
    public void onClick(View v)
    {
        login();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        switch (buttonView.getId())
        {
        case R.id.rmb_password_check:
            if (!isChecked)
            {
                auto_login.setChecked(false);
            }
            break;
        case R.id.auto_login_check:
            if (isChecked)
            {
                rmb_pwd.setChecked(true);
            }
            break;
        }
    }
}
